<template>
  <div class="container">
    <el-card shadow="hover">
      <div slot="header" style="font-size:18px;font-weight:bold">
        <i class="el-icon-circle-plus"></i> 新增常见害虫
      </div>

      <el-steps :active="stepActive" simple finish-status="success" style="margin-top:20px">
        <el-step title="填写基本信息" icon="el-icon-edit"></el-step>
        <el-step title="上传图片" icon="el-icon-picture"></el-step>
        <el-step title="完成" icon="el-icon-check"></el-step>
      </el-steps>

      <!-- 步骤一：填写基本信息 -->
      <div v-show="stepActive === 0">
        <el-form :model="form"
                 :rules="rules"
                 ref="ruleForm"
                 label-width="130px"                 style="margin-top:30px">

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="害虫名称" prop="name">
                <el-input v-model="form.name" placeholder="例如：棉叶螨"/>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="分类" prop="categories">
                <el-select v-model="form.categories"
                           multiple
                           placeholder="请选择分类（可多选）"                           style="width:100%">
                  <el-option v-for="item in categoryOptions"
                             :key="item.id"
                             :label="item.name"
                             :value="item.name"/>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="基本信息" prop="basicInformation">
            <el-input v-model="form.basicInformation" type="textarea" :rows="2"/>
          </el-form-item>
          <el-form-item label="形态特征" prop="morphologicalCharacteristics">
            <el-input v-model="form.morphologicalCharacteristics" type="textarea" :rows="2"/>
          </el-form-item>
          <el-form-item label="生活习性" prop="livingHabits">
            <el-input v-model="form.livingHabits" type="textarea" :rows="2"/>
          </el-form-item>
          <el-form-item label="发生规律" prop="occurrencePattern">
            <el-input v-model="form.occurrencePattern" type="textarea" :rows="2"/>
          </el-form-item>
          <el-form-item label="危害特点" prop="hazardCharacteristics">
            <el-input v-model="form.hazardCharacteristics" type="textarea" :rows="2"/>
          </el-form-item>
          <el-form-item label="防治方法" prop="controlMethods">
            <el-input v-model="form.controlMethods" type="textarea" :rows="2"/>
          </el-form-item>

          <el-form-item class="footer-buttons">
            <el-button type="primary" icon="el-icon-check" @click="save" :loading="loading">保存基本信息</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 步骤二：上传图片 -->
      <div v-show="stepActive === 1">
        <div style="text-align:center;margin:30px 0">
          <el-upload ref="upload"
                     name="file"
                     :file-list="fileList"
                     multiple
                     accept="image/*"
                     list-type="picture-card"
                     :action="uploadAction"
                     :before-upload="beforeUpload"
                     :on-success="handleSuccess"
                     :on-error="handleError"
                     :auto-upload="false">
            <i class="el-icon-plus avatar-uploader-icon"></i>
            <div slot="tip" class="el-upload__tip">支持多选，建议 1:1，单张≤2MB</div>
          </el-upload>
        </div>

        <div class="footer-buttons">
          <el-button @click="stepActive = 0">上一步</el-button>
          <el-button type="primary" @click="submitUpload">上传图片</el-button>
          <el-button @click="finish">直接完成</el-button>
        </div>
      </div>

      <!-- 步骤三：完成 -->
      <div v-show="stepActive === 2" style="text-align:center;padding:50px 0">
        <i class="el-icon-circle-check" style="font-size:72px;color:#67C23A"></i>
        <p style="font-size:20px;margin:20px 0">新增害虫成功！</p>
        <el-button type="primary" icon="el-icon-back" @click="$router.push('/verminList')">返回列表</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>import request from '@/utils/request'
import Cookies from 'js-cookie'

export default {
  name: 'AddPest',
  data() {
    return {
      stepActive: 0,
      loading: false,
      form: {
        name: '',
        basicInformation: '',
        morphologicalCharacteristics: '',
        livingHabits: '',
        occurrencePattern: '',
        hazardCharacteristics: '',
        controlMethods: '',
        categories: []
      },
      rules: {
        name: [{ required: true, message: '请输入害虫名称', trigger: 'blur' }],
        categories: [{ type: 'array', min: 1, message: '请至少选择一个分类', trigger: 'change' }],
        basicInformation: [{ required: true, message: '请输入基本信息', trigger: 'blur' }],
        morphologicalCharacteristics: [{ required: true, message: '请输入形态特征', trigger: 'blur' }],
        livingHabits: [{ required: true, message: '请输入生活习性', trigger: 'blur' }],
        occurrencePattern: [{ required: true, message: '请输入发生规律', trigger: 'blur' }],
        hazardCharacteristics: [{ required: true, message: '请输入危害特点', trigger: 'blur' }],
        controlMethods: [{ required: true, message: '请输入防治方法', trigger: 'blur' }]
      },
      categoryOptions: [],
      fileList: [],
      uploadAction: '',
      pestId: null,
      uploadUrls: [] // 用于存储上传成功的URL
    }
  },
  created() {
    // 初始化时使用占位符URL
    this.uploadAction = `${process.env.VUE_APP_BASEURL}/api/pest/upload/__PLACEHOLDER__/images`
    this.loadCategories()
  },
  methods: {

    /* 分类下拉 */
    loadCategories() {
      request.get('/category/tree').then(res => {
        this.categoryOptions = this.flatTree(res.data || [])
      })
    },
    flatTree(tree) {
      let arr = []
      tree.forEach(n => {
        arr.push({ id: n.id, name: n.name })
        if (n.children && n.children.length) arr = arr.concat(this.flatTree(n.children))
      })
      return arr
    },
    /* 保存文本 */
    save() {
      this.$refs.ruleForm.validate(valid => {
        if (!valid) return
        this.loading = true
        request.post('/pest/save', this.form).then(res => {
          this.loading = false
          if (res.code === '200') {
            this.$message.success('基本信息已保存')
            this.stepActive = 1
            const pestId = res.data // 后端返回自增 id
            // 正确设置上传地址
            this.uploadAction = `${process.env.VUE_APP_BASEURL}/api/image/upload/${pestId}`
            // 如果使用了 Element UI 的 ref，也需要更新其 action 属性
            this.$nextTick(() => {
              if (this.$refs.upload) {
                this.$refs.upload.action = this.uploadAction
              }
              // 如果有图片则自动上传
              if (this.$refs.upload && this.$refs.upload.uploadFiles && this.$refs.upload.uploadFiles.length) {
                // 不再自动上传，让用户手动点击上传按钮
                // this.$refs.upload.submit()
              }
            })
          } else {
            this.$message.error(res.msg || '保存失败')
          }
        }).catch(error => {
          this.loading = false
          console.error("保存基本信息时出错:", error)
          this.$message.error('保存失败: ' + (error.message || '网络错误'))
        })
      })
    },
    /* 上传相关方法 */
    beforeUpload(file) {
      const isImg = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isImg) this.$message.error('只能上传 JPG/PNG 图片')
      if (!isLt2M) this.$message.error('单张图片不超过 2MB')
      return isImg && isLt2M
    },
    /* 上传成功回调 */
    handleSuccess(res, file, fileList) {
      if (res.code === '200') {
        this.uploadUrls = res.data || []; // 保存上传成功的图片地址
        this.$notify.success('图片上传成功');
        if (fileList.every(f => f.status === 'success')) {
          this.stepActive = 2;
          this.$notify.success('新增害虫完成！');
        }
      } else {
        this.$message.error(res.msg || '图片上传失败');
      }
    },
    handleError(err, file, fileList) {
      console.error('上传失败:', err)
      this.$message.error('图片上传失败，请重试')
    },
    /* 手动触发上传 */
    submitUpload() {
      if (!this.$refs.upload || !this.$refs.upload.uploadFiles || this.$refs.upload.uploadFiles.length === 0) {
        this.$message.warning('请先选择要上传的图片')
        return
      }
      // 确保URL中的占位符已被替换
      if (this.uploadAction.includes('__PLACEHOLDER__')) {
        this.$message.error('请先保存基本信息')
        return
      }
      this.$refs.upload.submit()
    },
    /* 直接完成 */
    finish() {
      this.stepActive = 2
      this.$notify.success('新增害虫完成！')
    }
  }
}
</script>

<style scoped>.container {
  width: 80%;
  margin: 20px auto
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 148px;
  height: 148px;
  line-height: 148px;
  text-align: center
}

.footer-buttons {
  text-align: center;
  margin-top: 30px
}
</style>
